<?php

namespace app\api\controller;

use app\common\controller\Api;
use  app\admin\model\Users as userss;
//use tests\thinkphp\library\think\log\driver\fileTest;
use  think\Db;
use think\Env;
use fast\Random;

/**
 * 我的
 */
class My extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    private $redis;
    private $openid;
    private $user_arr;

    public function _initialize()
    {
        parent::_initialize();

        $this->redis = redis(Env::get('redis.host'), Env::get('redis.port'), Env::get('redis.pwd'), Env::get('redis.db'));

        $this->openid = empty($_SERVER['HTTP_OPENID']) ? $this->error('openid不能为空',[],'401'):$_SERVER['HTTP_OPENID'];//获取openid

        $this->user_arr = Db::table('fa_users')
            ->where('openid',$this->openid)
            ->find();

        if (empty($this->user_arr)){
            $this->error('用户信息为空',[],'401');
        }

    }



    /**
     * 获取用户信息
     *
     */
    public function get_userinfo(){

        $data = Db::table('fa_users')
            ->field('id,nickname,phone,level,integral,money,image,pid,count')
            ->where('openid',$this->openid)
            ->find();

        $count = Db::table('fa_info')
            ->where('user_id',$this->user_arr['id'])
            ->where('is_del',0)
            ->count();

        switch ($data['level']){
            case 1:
                $family = 1;
                break;
            case 2:
                $family = 1;
                break;
            case 3:
                $family = 1;
                break;
            case 4:
                $family = 3;
                break;
            case 5:
                $family = 5;
                break;
            case 6:
                $family = 6;
                break;
            case 7:
                $family = 7;
                break;
            case 8:
                $family = 8;
                break;
            case 9:
                $family = 9;
                break;
        }
        $data['is_info'] = $count;
        $data['family'] = $data['count'];

        $treatment = Db::table('fa_treatment')
            ->alias('a')
            ->field('a.*')
            ->join('fa_diagnosis_order b','a.order_id=b.id')
            ->join('fa_info c','b.info_id=c.id')
            ->where(['c.user_id'=>$data['id'],'finish'=>0])
            ->order('date','asc')
            ->select();

        if (!empty($treatment)){
            foreach ($treatment as $k=>$v){
                if ($v['date'] < date('Y-m-d')){
                    unset($treatment[$k]);
                }
            }

            $treatment = array_merge($treatment);
            if(!empty($treatment)){
                $treatments = $treatment[0]['date'];
            }else{
                $treatments = '';
            }


        }else{
            $treatments = '';
        }

        $data['treatment'] = $treatments;

        $big_arr = Db::table('fa_big')
            ->where('phone',$data['phone'])
            ->find();

        $data['is_big'] = 0;
        if (!empty($big_arr)){
            $data['is_big'] = 1;
        }

        $this->success('查询成功',$data);
    }


    /**
     * 添加就诊人信息接口
     *
     */
    public function add_info(){
        $name = empty(request()->post('name')) ? $this->error('name不能为空'):request()->post('name');//获取name
        $sex = empty(request()->post('sex')) ? $this->error('sex不能为空'):request()->post('sex');//获取sex
        $nation = empty(request()->post('nation')) ? $this->error('nation不能为空'):request()->post('nation');//获取nation
        $id_card = empty(request()->post('id_card')) ? $this->error('id_card不能为空'):request()->post('id_card');//获取id_card
        $mobile = empty(request()->post('mobile')) ? $this->error('mobile不能为空'):request()->post('mobile');//获取mobile
        $relation = empty(request()->post('relation')) ? $this->error('relation不能为空'):request()->post('relation');//获取relation
        $nationality = empty(request()->post('nationality')) ? $this->error('nationality不能为空'):request()->post('nationality');//获取nationality
        $birthday = empty(request()->post('birthday')) ? $this->error('birthday不能为空'):request()->post('birthday');//获取birthday
        $birthplace = empty(request()->post('birthplace')) ? $this->error('birthplace不能为空'):request()->post('birthplace');//获取birthplace
        $address = empty(request()->post('address')) ? $this->error('address不能为空'):request()->post('address');//获取address

        $binding = empty(request()->post('binding')) ? '':request()->post('binding');

        $mobile = is_phone($mobile);

        if ($mobile === false){
            $this->error('手机号格式错误');
        }

        if ($this->user_arr['pid'] != 0){
            $this->error('该用户不能添加就诊人');
        }

        $pan = Db::table('fa_info')
            ->where('user_id',$this->user_arr['id'])
            ->count();
        //判断会员添加次数

        if ($this->user_arr['count'] < $pan+1){
            $this->error('该用户只能添加'.$this->user_arr['count'].'个就诊信息');
        }

        if ($relation == '本人'){
            //判断关系、本人
            $relation_pan = Db::table('fa_info')
                ->where(['user_id'=>$this->user_arr['id'],'relation'=>'本人'])
                ->count();

            if ($relation_pan > 0){
                $this->error('已存在本人,请重新选择');
            }
        }


        if ($relation == '配偶'){
            //判断关系、配偶
            $relations = Db::table('fa_info')
                ->where(['user_id'=>$this->user_arr['id'],'relation'=>'配偶'])
                ->count();

            if ($relations > 0){
                $this->error('已存在配偶,请重新选择');
            }
        }


        $card = Db::table('fa_info')
            ->where('id_card',$id_card)
            ->find();

        if ($card['is_del'] != 1){
            if (!empty($card)){
                $this->error('该身份证已存在,请重新填写');
            }
        }



        //开启事务
        Db::startTrans();

        if (!empty($binding)){
            $binding_arr = Db::table('fa_users')
                ->where('id',$binding)
                ->find();

            $pan_arrs = Db::table('fa_info')
                ->where('user_id',$binding)
                ->count();

            if ($pan_arrs > 0){
                $this->error('该账户不能绑定');
            }

            if (empty($binding_arr)){
                $this->error('绑定用户数据为空');
            }

            if ($binding_arr['pid'] != 0){
                $this->error('该用户已被绑定');
            }

            if ($binding == $this->user_arr['id']){
                $update = 1;
            }else{
                $update = Db::table('fa_users')
                    ->where('id',$binding)
                    ->update([
                        'level' => $this->user_arr['level'],
                        'pid' => $this->user_arr['id'],
                        'vip_time' => $this->user_arr['vip_time'],
                        'count' => $this->user_arr['count'],
                        'update_time' => time(),
                    ]);
            }




        }else{
            $update = 1;
        }


        $is_in = Db::table('fa_info')
            ->where(['id_card'=>$id_card])
            ->find();

        if (empty($is_in)){
            $number = 'looin'.get_strings(6,2);
            $insert = Db::table('fa_info')
                ->insertGetId([
                    'user_id' => $this->user_arr['id'],
                    'name' => $name,
                    'sex' => $sex,
                    'nation' => $nation,
                    'id_card' => $id_card,
                    'mobile' => $mobile,
                    'relation' => $relation,
                    'nationality' => $nationality,
                    'birthday' => $birthday,
                    'birthplace' => $birthplace,
                    'address' => $address,
                    'number' => $number,
                    'create_time' => time(),
                    'binding' => $binding,
                ]);
        }else{
            $insert = Db::table('fa_info')
                ->where('id',$is_in['id'])
                ->update([
                    'user_id' => $this->user_arr['id'],
                    'name' => $name,
                    'sex' => $sex,
                    'nation' => $nation,
                    //'id_card' => $id_card,
                    'mobile' => $mobile,
                    'relation' => $relation,
                    'nationality' => $nationality,
                    'birthday' => $birthday,
                    'birthplace' => $birthplace,
                    'address' => $address,
                    //'number' => $number,
                    'update_time' => time(),
                    'binding' => $binding,
                    'is_del' => 0,
                ]);
        }


        if (($insert !== false) && ($update !== false)){
            //事务提交
            Db::commit();
            $this->success('添加成功',[]);
        }else{
            //事务回滚
            Db::rollback();
            $this->error('添加失败');
        }

    }

    /**
     * 获取就诊人信息列表
     *
     */
    public function info_list(){
        if ($this->user_arr['pid'] == 0){
            $data = Db::table('fa_info')
                ->field('id,name,sex,relation,id_card,birthday')
                ->where('user_id',$this->user_arr['id'])
                ->where('is_del',0)
                ->order('id','desc')
                ->select();
        }else{
            $data = Db::table('fa_info')
                ->field('id,name,sex,relation,id_card,birthday')
                ->where('binding',$this->user_arr['id'])
                ->where('is_del',0)
                ->order('id','desc')
                ->select();
        }



        if (!empty($data)){
            foreach ($data as $k=>$v){
                $data[$k]['age'] =countage($v['birthday']);
            }
        }

        $this->success('查询成功',$data);

    }


    /**
     * 获取就诊人详情接口
     *
     */
    public function get_info(){
        $id = empty(request()->post('id')) ? 0:request()->post('id');//获取id

        if ($id == 0){

            if ($this->user_arr['pid'] == 0){
                $data = Db::table('fa_info')
                    ->field('id,name,sex,nation,id_card,mobile,relation,nationality,birthday,birthplace,address,number,binding')
                    ->where('user_id',$this->user_arr['id'])
                    ->where('is_del',0)
                    ->order('id','desc')
                    ->find();
            }else{
                $data = Db::table('fa_info')
                    ->field('id,name,sex,nation,id_card,mobile,relation,nationality,birthday,birthplace,address,number,binding')
                    ->where('binding',$this->user_arr['id'])
                    ->where('is_del',0)
                    ->order('id','desc')
                    ->find();
            }

        }else{
            $data = Db::table('fa_info')
                ->field('id,name,sex,nation,id_card,mobile,relation,nationality,birthday,birthplace,address,number,binding')
                ->where('id',$id)
                ->find();
        }


        if ($data['binding'] != 0){
            $pid_name = Db::table('fa_users')
                ->field('id,nickname')
                ->where('id',$data['binding'])
                ->find();
        }else{
            $pid_name = [];
        }


        if (!empty($data)){
            $data['age'] =countage($data['birthday']);
            $data['pid_name'] = empty($pid_name) ? '':$pid_name['nickname'];
        }

        $list = [
            'info' => $data,
            'life' => [],
            'health' => [],
            'report' => [],
        ];

        $this->success('查询成功',$list);
    }

    /**
     * 编辑就诊人数据
     *
     */
    public function update_info(){
        $id = empty(request()->post('id')) ? $this->error('id不能为空'):request()->post('id');//获取id
        $name = empty(request()->post('name')) ? $this->error('name不能为空'):request()->post('name');//获取name
        $sex = empty(request()->post('sex')) ? $this->error('sex不能为空'):request()->post('sex');//获取sex
        $nation = empty(request()->post('nation')) ? $this->error('nation不能为空'):request()->post('nation');//获取nation
        $id_card = empty(request()->post('id_card')) ? $this->error('id_card不能为空'):request()->post('id_card');//获取id_card
        $mobile = empty(request()->post('mobile')) ? $this->error('mobile不能为空'):request()->post('mobile');//获取mobile
        $relation_name = empty(request()->post('relation')) ? $this->error('relation不能为空'):request()->post('relation');//获取relation
        $nationality = empty(request()->post('nationality')) ? $this->error('nationality不能为空'):request()->post('nationality');//获取nationality
        $birthday = empty(request()->post('birthday')) ? $this->error('birthday不能为空'):request()->post('birthday');//获取birthday
        $birthplace = empty(request()->post('birthplace')) ? $this->error('birthplace不能为空'):request()->post('birthplace');//获取birthplace
        $address = empty(request()->post('address')) ? $this->error('address不能为空'):request()->post('address');//获取address


        $binding = empty(request()->post('binding')) ? '':request()->post('binding');

        if ($relation_name == '本人'){
            //判断关系、本人
            $relation = Db::table('fa_info')
                ->where(['user_id'=>$this->user_arr['id'],'relation'=>'本人'])
                ->count();

            if ($relation > 0){
                $this->error('已存在本人,请重新选择');
            }
        }


        if ($relation_name == '配偶'){
            //判断关系、配偶
            $relations = Db::table('fa_info')
                ->where(['user_id'=>$this->user_arr['id'],'relation'=>'配偶'])
                ->count();

            if ($relations > 0){
                $this->error('已存在配偶,请重新选择');
            }
        }


        $card = Db::table('fa_info')
            ->where('id_card',$id_card)
            ->find();
        if (!empty($card)){
            $cards = Db::table('fa_info')
                ->where(['id'=>$id,'id_card'=>$id_card])
                ->find();
            if (empty($cards)){
                $this->error('该身份证已存在,请重新填写');
            }
        }

        //开启事务
        Db::startTrans();

        if (!empty($binding)){
            $binding_arr = Db::table('fa_users')
                ->where('id',$binding)
                ->find();

            $pan_arrs = Db::table('fa_info')
                ->where('user_id',$binding)
                ->count();

            if ($pan_arrs > 0){
                $this->error('该账户不能绑定');
            }

            if (empty($binding_arr)){
                $this->error('绑定用户数据为空');
            }

            if ($binding_arr['pid'] != 0){
                $this->error('该用户已被绑定');
            }

            if ($binding == $this->user_arr['id']){
                $updates = 1;
            }else{
                $updates = Db::table('fa_users')
                    ->where('id',$binding)
                    ->update([
                        'level' => $this->user_arr['level'],
                        'pid' => $this->user_arr['id'],
                        'vip_time' => $this->user_arr['vip_time'],
                        'count' => $this->user_arr['count'],
                        'update_time' => time(),
                    ]);
            }


            $update = Db::table('fa_info')
                ->where('id',$id)
                ->update([
                    'name' => $name,
                    'sex' => $sex,
                    'nation' => $nation,
                    'id_card' => $id_card,
                    'mobile' => $mobile,
                    'relation' => $relation_name,
                    'nationality' => $nationality,
                    'birthday' => $birthday,
                    'birthplace' => $birthplace,
                    'address' => $address,
                    'update_time' => time(),
                    'binding' => $binding,
                ]);

        }else{
            $updates = 1;

            $update = Db::table('fa_info')
                ->where('id',$id)
                ->update([
                    'name' => $name,
                    'sex' => $sex,
                    'nation' => $nation,
                    'id_card' => $id_card,
                    'mobile' => $mobile,
                    'relation' => $relation_name,
                    'nationality' => $nationality,
                    'birthday' => $birthday,
                    'birthplace' => $birthplace,
                    'address' => $address,
                    'update_time' => time(),
                    //'binding' => $binding,
                ]);
        }




        if (($update !== false) && ($updates !== false)){
            //事务提交
            Db::commit();
            $this->success('成功',[]);
        }else{
            //事务回滚
            Db::rollback();
            $this->error('失败');
        }
    }

    /**
     * 获取挂号费金额
     *
     */
    public function get_money(){
        $id = empty(request()->post('id')) ? $this->error('id不能为空'):request()->post('id');//获取id

        $medic = Db::table('fa_medic')
            ->where('id',$id)
            ->find();

        $this->success('成功',$medic['registration_fee']);
    }


    /**
     * 获取预约咨询列表数据
     *
     */
    public function get_registration(){
        $id = empty(request()->post('id')) ? '':request()->post('id');//获取id
        $date = empty(request()->post('date')) ? '':request()->post('date');//获取date
        $status = empty(request()->post('status')) ? '':request()->post('status');//获取status
        $page = empty(request()->post('page')) ? 1:request()->post('page');//获取页码
        $limt = empty(request()->post('limt')) ? 5:request()->post('limt');//获取每页显示条数


        //分页
        if ($page == 1) {
            $page_start = 0;
            $page_end = $limt-1;
        } else {
            $page_start = ($page - 1) * $limt;
            $page_end = $page_start + $limt-1;
        }

        $where = [];
        if (!empty($id)){
            $where['a.info_id'] = $id;
        }

        if (!empty($status)){
            $where['a.status'] = $status;
        }

        $a = get_week(time());


        if (!empty($date)){
            if ($date == 1){
                $where['a.date'] = date('Y-m-d');
            }elseif ($date == 2){
                $where['a.date'] = ['between time',[$a[0]['date'],$a[6]['date']]];
            }
        }


        if ($this->user_arr['pid'] == 0){
            $data = Db::table('fa_registration')
                ->alias('a')
                ->field('a.id,a.code,a.status,b.name,a.visiting_time,a.price,a.info_id,a.medic_id,a.project')
                ->join('fa_info b','a.info_id=b.id')
                //->where('a.user_id',$this->user_arr['id'])
                ->where('b.user_id',$this->user_arr['id'])
                ->where($where)
                ->limit($page_start,$limt)
                ->order('id','desc')
                ->select();

            $total = Db::table('fa_registration')
                ->alias('a')
                ->join('fa_info b','a.info_id=b.id')
                //->where('a.user_id',$this->user_arr['id'])
                ->where('b.user_id',$this->user_arr['id'])
                ->where($where)
                ->count();
        }else{
            $data = Db::table('fa_registration')
                ->alias('a')
                ->field('a.id,a.code,a.status,b.name,a.visiting_time,a.price,a.info_id,a.medic_id,a.project')
                ->join('fa_info b','a.info_id=b.id')
                ->where('a.user_id',$this->user_arr['id'])
                ->where($where)
                ->limit($page_start,$limt)
                ->order('id','desc')
                ->select();

            $total = Db::table('fa_registration')
                ->alias('a')
                ->join('fa_info b','a.info_id=b.id')
                ->where('a.user_id',$this->user_arr['id'])
                ->where($where)
                ->count();
        }



        if (!empty($data)){
            foreach ($data as $k=>$v){
                $data[$k]['price'] = $v['price']*100;
                if ($v['status'] == '待就诊'){
                    $data[$k]['status'] = '待咨询';
                }
            }
        }


        //组装数据
        $datas = [
            'page' => $page,
            'total' => $total,
            'limt' => $limt,
            'list' => $data,
        ];

        $this->success('成功',$datas);
    }


    /**
     * 获取预约挂号详情
     *
     */
    public function registration_details(){
        $code = empty(request()->post('code')) ? $this->error('code不能为空'):request()->post('code');//获取code
        $phone = $this->redis->hGet('humeng:set','phone');
        $address = $this->redis->hGet('humeng:set','address');
        $longitude = $this->redis->hGet('humeng:set','longitude');
        $latitude = $this->redis->hGet('humeng:set','latitude');

        $data = Db::table('fa_registration')
            ->alias('a')
            ->field('a.id,a.code,a.status,b.name,a.visiting_time,c.name as names,a.project,a.project_ids,a.price,a.create_time')
            ->join('fa_info b','a.info_id=b.id','left')
            ->join('fa_medic c','a.medic_id=c.id','left')
            ->where('a.code',$code)
            ->find();

        $data['create_time'] = date('Y-m-d H:i:s',$data['create_time']);
        $data['pay'] = '微信支付';
        $data['phone'] = $phone;
        $data['address'] = $address;
        $data['longitude'] = $longitude;
        $data['latitude'] = $latitude;

        if ($data['status'] == '待就诊'){
            $data['status'] = '待咨询';
        }

        $this->success('成功',$data);
    }

    /**
     * 变更日期
     *
     */
    public function edit_registration(){
        $id = empty(request()->post('id')) ? $this->error('id不能为空'):request()->post('id');
        $working_id = empty(request()->post('working_id')) ? $this->error('working_id不能为空'):request()->post('working_id');


        $data_working = Db::table('fa_working')
            ->where('id',$working_id)
            ->find();

        if (empty($data_working)){
            $this->error('预约时间不存在',[]);
        }else{
            $date = date("w",strtotime($data_working['date']));

            switch ($data_working['time']){
                case 1:
                    if (date('Y-m-d H:i:s') > $data_working['date'].' 10:00:00'){
                        $this->error('预约时间已超时',[]);
                    }
                    $tims = '09:00-10:00';
                    break;
                case 2:
                    if (date('Y-m-d H:i:s') > $data_working['date'].' 11:00:00'){
                        $this->error('预约时间已超时',[]);
                    }
                    $tims = '10:00-11:00';
                    break;
                case 3:
                    if (date('Y-m-d H:i:s') > $data_working['date'].' 12:00:00'){
                        $this->error('预约时间已超时',[]);
                    }
                    $tims = '11:00-12:00';
                    break;
                case 4:
                    if (date('Y-m-d H:i:s') > $data_working['date'].' 15:00:00'){
                        $this->error('预约时间已超时',[]);
                    }
                    $tims = '14:00-15:00';
                    break;
                case 5:
                    if (date('Y-m-d H:i:s') > $data_working['date'].' 16:00:00'){
                        $this->error('预约时间已超时',[]);
                    }
                    $tims = '15:00-16:00';
                    break;
                case 6:
                    if (date('Y-m-d H:i:s') > $data_working['date'].' 17:00:00'){
                        $this->error('预约时间已超时',[]);
                    }
                    $tims = '16:00-17:00';
                    break;
                default:
                    $this->error('预约时间错误');
                    break;
            }

            switch ($date){
                case 0:
                    $day = '星期天';
                    break;
                case 1:
                    $day = '星期一';
                    break;
                case 2:
                    $day = '星期二';
                    break;
                case 3:
                    $day = '星期三';
                    break;
                case 4:
                    $day = '星期四';
                    break;
                case 5:
                    $day = '星期五';
                    break;
                case 6:
                    $day = '星期六';
                    break;
                default:
                    $day = '';
                    break;
            }
            $visiting_time = $data_working['date'].' '.$day.' '.$tims;
            $datess = $data_working['date'];
        }


        $update = Db::table('fa_registration')
            ->where('id',$id)
            ->update([
                'visiting_time' => $visiting_time,
                'working_id' => $working_id,
                'date' => $datess,
                'update_time' => time(),
            ]);

        if ($update !== false){
            $this->success('成功',[]);
        }else{
            $this->error('失败',[]);
        }
    }

    /**
     * 我的会员列表接口
     *
     */
    public function get_vip(){
        //$level = empty(request()->post('level')) ? $this->user_arr['level']:request()->post('level');

        $data = Db::table('fa_vip_level')
            ->where('level',$this->user_arr['level'])
            ->find();

        $count = Db::table('fa_info')
            ->where('user_id',$this->user_arr['id'])
            ->count();

        $vip_arr = Db::table('fa_vip_card')
            ->where('id',$this->user_arr['vip'])
            ->find();

        $lists = [];

        for ($i=1;$i<=3;$i++){
            $list = Db::table('fa_vip_relation')
                ->alias('a')
                ->field('a.id,b.name,a.status,c.level_name')
                ->join('fa_vip_serve b','a.serve_id=b.id','left')
                ->join('fa_vip_level c','a.level_id=c.id','left')
                ->where('a.level_id',$i)
                ->select();

            if (!empty($list)){
                foreach ($list as $k=>$v){
                    switch ($v['status']){
                        case 0:
                            $list[$k]['status_name'] = '免费';
                            break;
                        case 1:
                            $list[$k]['status_name'] = '免1次';
                            break;
                        case 2:
                            $list[$k]['status_name'] = '免1次/年 ';
                            break;
                        case 3:
                            $list[$k]['status_name'] = '免2次/年';
                            break;
                        case 4:
                            $list[$k]['status_name'] = '免3次/年';
                            break;
                    }

                    $names = $list[$k]['level_name'];
                    unset($list[$k]['status']);
                    unset($list[$k]['level_name']);
                }
            }

//            if ($this->user_arr['vip'] != 0){
//                if ($this->user_arr['level'] == $i){
//                    $list[] = [
//                        'id' => 0,
//                        'name' => '健康项目',
//                        'status_name' => number_format($vip_arr['discount'],1,'.','').'折优惠',
//                    ];
//                }
//
//            }


            switch ($i){
                case 1:
                    if (!empty($list)){
                        $lists = [];
                        foreach ($list as $k=>$v){
                            if ($v['id'] == 0){
                                $lists = [$v];
                            }
                        }
                        $list = $lists;
                    }else{
                        $list = [];
                    }
                    $counts = 1;
                    break;
                case 2:
                    $counts = 1;
                    break;
                case 3:
                    if ($this->user_arr['level'] == 3){
                        $counts = $this->user_arr['count'];
                    }else{
                        $counts = 8;
                    }

                    break;
            }

            if ($this->user_arr['level'] > $i){
                $is_level = 2;
            }elseif ($this->user_arr['level'] == $i){
                $is_level = 1;
            }else{
                $is_level = 0;
            }


            $lists[$i-1]['level'] = $i;
            $lists[$i-1]['level_name'] = $names;
            $lists[$i-1]['counts'] = $counts;
            $lists[$i-1]['is_level'] = $is_level;
            $lists[$i-1]['data'] = $list;

        }


        if ($this->user_arr['level'] == 1){
            if (empty($this->user_arr['vip_time'])){
                $vip_time = '长期';
            }else{
                $vip_time = $this->user_arr['vip_time'];
            }
        }else{
            if (empty($this->user_arr['vip_time'])){
                $vip_time = '';
            }else{
                $vip_time = $this->user_arr['vip_time'];
            }
        }

        $arr = [
            'level' => $this->user_arr['level'],
            'level_name' => $data['level_name'],
            'integral' => $this->user_arr['integral'],
            'count' => $count,
            'vip_time' => $vip_time,
            'vip' => $this->user_arr['vip'],
            'vip_name' => empty($vip_arr) ? '': $vip_arr['name'],
            'list' => $lists,
        ];


        $this->success('成功',$arr);
    }

    /**
     *
     * 点赞/取消点赞
     */
    public function praise(){
        $id = empty(request()->post('id')) ? $this->error('id不能为空'):request()->post('id');

        $praise = isset(request()->post()['praise']) ? request()->post('praise'):$this->error('praise不能为空');

        $arr = Db::table('fa_praise')
            ->where(['user_id'=>$this->user_arr['id'],'book_id'=>$id])
            ->find();

        //开启事务
        Db::startTrans();

        if ($praise == 0){
            $in = Db::table('fa_book')
                ->where('id',$id)
                ->setDec('give_count',1);
        }elseif ($praise == 1){
            $in = Db::table('fa_book')
                ->where('id',$id)
                ->setInc('give_count',1);
        }else{
            $this->error('praise参数错误',[]);
        }

        if (empty($arr)){
            $inserts = Db::table('fa_praise')
                ->insertGetId([
                    'user_id' => $this->user_arr['id'],
                    'book_id' => $id,
                    'praise' => $praise,
                    'create_time' => time(),
                ]);
        }else{
            if ($arr['user_id'] != $this->user_arr['id']){
                $this->error('点赞人错误',[]);
            }

            $inserts = Db::table('fa_praise')
                ->where('id',$arr['id'])
                ->update([
                    'praise' => $praise,
                    'update_time' => time(),
                ]);
        }

        if (($in !== false) && ($inserts !== false)){
            //提交事务
            Db::commit();
            $this->success('成功',['is_praise'=>$praise]);
        }else{
            //事务回滚
            Db::rollback();
            $this->error('失败',[]);
        }

    }

    /**
     * 服务记录
     *
     */
    public function order_log(){
        $info_id = empty(request()->post('id')) ? '':request()->post('id');
        $date = empty(request()->post('date')) ? '':request()->post('date');

        $page = empty(request()->post('page')) ? 1:request()->post('page');//获取页码
        $limt = empty(request()->post('limt')) ? 10:request()->post('limt');//获取每页显示条数

        $user_id = $this->user_arr['id'];

        //分页
        if ($page == 1) {
            $page_start = 0;
            $page_end = $limt-1;
        } else {
            $page_start = ($page - 1) * $limt;
            $page_end = $page_start + $limt-1;
        }

        $where = [];
        if (!empty($info_id)){
            $where['b.info_id'] = $info_id;
        }

        if (!empty($date)){

            if ($date == 1){
                $where['a.date'] = date('Y-m-d');
            }elseif ($date == 2){
                $where['a.date'] = ['between time', [date('Y-m-d'), date('Y-m-d',strtotime('+6 days'))]];
            }
        }


        if ($this->user_arr['pid'] == 0){
            $data = Db::table('fa_treatment')
                ->alias('a')
                ->field('a.id,a.order_id,b.code,c.name,a.name as names,a.date')
                ->join('fa_diagnosis_order b','a.order_id=b.id')
                ->join('fa_info c','b.info_id=c.id')
                ->where($where)
                ->where('c.user_id',$user_id)
                ->limit($page_start,$limt)
                ->order('date','desc')
                ->select();

            $total = Db::table('fa_treatment')
                ->alias('a')
                ->join('fa_diagnosis_order b','a.order_id=b.id')
                ->join('fa_info c','b.info_id=c.id')
                ->where('c.user_id',$user_id)
                ->where($where)
                ->count();
        }else{
            $data = Db::table('fa_treatment')
                ->alias('a')
                ->field('a.id,a.order_id,b.code,c.name,a.name as names,a.date')
                ->join('fa_diagnosis_order b','a.order_id=b.id')
                ->join('fa_info c','b.info_id=c.id')
                ->where($where)
                ->where('c.binding',$user_id)
                ->limit($page_start,$limt)
                ->order('date','desc')
                ->select();

            $total = Db::table('fa_treatment')
                ->alias('a')
                ->join('fa_diagnosis_order b','a.order_id=b.id')
                ->join('fa_info c','b.info_id=c.id')
                ->where('c.binding',$user_id)
                ->where($where)
                ->count();
        }


        if (!empty($data)){
            foreach ($data as $k=>$v){
                $count = Db::table('fa_treatment')
                    ->where('order_id',$v['order_id'])
                    ->count();
                $data[$k]['names'] = $v['names'].'(共'.$count.'次)';
            }
        }


        //组装数据
        $datas = [
            'page' => $page,
            'total' => $total,
            'limt' => $limt,
            'list' => $data,
        ];

        $this->success('成功',$datas);


    }

    /**
     * 历史健康信息
     *
     */
    public function health_list(){
        $info_id = empty(request()->post('info_id')) ? $this->error('info_id不能为空'):request()->post('info_id');
        $page = empty(request()->post('page')) ? 1:request()->post('page');//获取页码
        $limt = empty(request()->post('limt')) ? 10:request()->post('limt');//获取每页显示条数

        $user_id = $this->user_arr['id'];

        //分页
        if ($page == 1) {
            $page_start = 0;
            $page_end = $limt-1;
        } else {
            $page_start = ($page - 1) * $limt;
            $page_end = $page_start + $limt-1;
        }


        $data = Db::table('fa_diagnosis_order')
            ->alias('a')
            ->field('a.id,a.create_time')
            ->where('a.info_id',$info_id)
            ->limit($page_start,$limt)
            ->order('id','desc')
            ->select();

        $total = Db::table('fa_diagnosis_order')
            ->alias('a')
            ->field('a.id,a.create_time')
            ->where('a.info_id',$info_id)
            ->count();

        if (!empty($data)){
            foreach ($data as $k=>$v){
                $data[$k]['create_time'] = date('Y-m-d H:i:s',$v['create_time']);
            }
        }


        //组装数据
        $datas = [
            'page' => $page,
            'total' => $total,
            'limt' => $limt,
            'list' => $data,
        ];

        $this->success('成功',$datas);
    }

    /**
     * 健康信息详情
     *
     */
    public function health_detail(){
        $info_id = empty(request()->post('info_id')) ? $this->error('info_id不能为空'):request()->post('info_id');
        $id = empty(request()->post('id')) ? '':request()->post('id');

        $where = [];
        if (!empty($id)){
            $where['id'] = $id;
        }

        $data = Db::table('fa_diagnosis_order')
            ->field('id,height,weight,blood_pressure,sphygmus,appeal,now,before,physique,announcements,create_time')
            ->where($where)
            ->where('info_id',$info_id)
            ->order('id','desc')
            ->find();

        if (!empty($data)){
            $data['create_time'] = date('Y-m-d H:i:s',$data['create_time']);
        }

        $this->success('成功',$data);

    }


    /**
     * 历史检查报告信息
     *
     */
    public function report_list(){
        $info_id = empty(request()->post('info_id')) ? $this->error('info_id不能为空'):request()->post('info_id');
        $page = empty(request()->post('page')) ? 1:request()->post('page');//获取页码
        $limt = empty(request()->post('limt')) ? 10:request()->post('limt');//获取每页显示条数

        $user_id = $this->user_arr['id'];

        //分页
        if ($page == 1) {
            $page_start = 0;
            $page_end = $limt-1;
        } else {
            $page_start = ($page - 1) * $limt;
            $page_end = $page_start + $limt-1;
        }


        $data = Db::table('fa_report')
            ->alias('a')
            ->field('a.id,a.create_time')
            //->join('fa_diagnosis_order b','a.order_id=b.id')
            ->where('a.order_id',$info_id)
            ->limit($page_start,$limt)
            ->order('a.id','desc')
            ->select();

        $total = Db::table('fa_report')
            ->alias('a')
            //->join('fa_diagnosis_order b','a.order_id=b.id')
            ->where('a.order_id',$info_id)
            ->count();

        if (!empty($data)){
            foreach ($data as $k=>$v){
                $data[$k]['create_time'] = date('Y-m-d H:i:s',$v['create_time']);
            }
        }


        //组装数据
        $datas = [
            'page' => $page,
            'total' => $total,
            'limt' => $limt,
            'list' => $data,
        ];

        $this->success('成功',$datas);
    }


    /**
     * 检查报告详情
     *
     */
    public function report_detail(){
        $info_id = empty(request()->post('info_id')) ? $this->error('info_id不能为空'):request()->post('info_id');
        $id = empty(request()->post('id')) ? '':request()->post('id');

        $where = [];
        if (!empty($id)){
            $where['a.id'] = $id;
        }

        $data = Db::table('fa_report')
            ->alias('a')
            ->field('a.id,a.create_time')
            //->join('fa_diagnosis_order b','a.order_id=b.id')
            ->where('a.order_id',$info_id)
            ->where($where)
            ->order('id','desc')
            ->find();


        if (!empty($data)){
            $data['create_time'] = date('Y-m-d H:i:s',$data['create_time']);

            $logs_arr = Db::table('fa_report_log')
                ->field('id,title,check_time,image,video,file')
                ->where('report_id',$data['id'])
                ->select();

            $image_arr = [];
            $images_arr = [];

            $video_arr = [];
            $videos_arr = [];

            $file_arr = [];
            $files_arr = [];
            $i = 0;
            if (!empty($logs_arr)){
                foreach ($logs_arr as $ks=>$vs){
                    $i += 100;
                    $image_arr = explode(';',$vs['image']);
                    if (!empty($image_arr)){
                        foreach ($image_arr as $ki=>$vi){
                            if (!empty($vi)){
                                $images_arr[$ki+1000+$i]['id'] = $vs['id'];
                                $images_arr[$ki+1000+$i]['image'] = $vi;
                                $images_arr[$ki+1000+$i]['title'] = $vs['title'];
                                $images_arr[$ki+1000+$i]['check_time'] = $vs['check_time'];
                                $images_arr[$ki+1000+$i]['suffix'] = substr(strrchr($vi, '.'), 1);
                            }
                        }
                    }

                    $video_arr = explode(';',$vs['video']);

                    if (!empty($video_arr)){
                        foreach ($video_arr as $ki=>$vi){
                            if (!empty($vi)){
                                $videos_arr[$ki+1000+$i]['id'] = $vs['id'];
                                $videos_arr[$ki+1000+$i]['video'] = $vi;
                                $videos_arr[$ki+1000+$i]['title'] = $vs['title'];
                                $videos_arr[$ki+1000+$i]['check_time'] = $vs['check_time'];
                                $videos_arr[$ki+1000+$i]['suffix'] = substr(strrchr($vi, '.'), 1);
                            }
                        }
                    }

                    $file_arr = explode(';',$vs['file']);
                    if (!empty($file_arr)){
                        foreach ($file_arr as $ki=>$vi){
                            if (!empty($vi)){
                                $files_arr[$ki+1000+$i]['id'] = $vs['id'];
                                $files_arr[$ki+1000+$i]['file'] = $vi;
                                $files_arr[$ki+1000+$i]['title'] = $vs['title'];
                                $files_arr[$ki+1000+$i]['check_time'] = $vs['check_time'];
                                $files_arr[$ki+1000+$i]['suffix'] = substr(strrchr($vi, '.'), 1);
                            }
                        }
                    }

                }

                $data['image'] = array_merge($images_arr);
                $data['video'] = array_merge($videos_arr);
                $data['file'] = array_merge($files_arr);
            }

        }

        $this->success('成功',$data);

    }

    /**
     * 密码查看图片
     *
     */
    public function report_password(){
        $password = empty(request()->post('password')) ? $this->error('password不能为空'):request()->post('password');

        if ($password == $this->user_arr['password']){
            $this->success('成功',[]);
        }else{
            $this->error('密码错误',[]);
        }
    }

    /**
     * 建议反馈列表
     *
     */
    public function feedback_list(){
        $info_id = empty(request()->post('id')) ? '':request()->post('id');
        $date = empty(request()->post('date')) ? '':request()->post('date');
        $feedback = empty(request()->post('feedback')) ? '':request()->post('feedback');

        $page = empty(request()->post('page')) ? 1:request()->post('page');//获取页码
        $limt = empty(request()->post('limt')) ? 10:request()->post('limt');//获取每页显示条数

        $user_id = $this->user_arr['id'];

        //分页
        if ($page == 1) {
            $page_start = 0;
            $page_end = $limt-1;
        } else {
            $page_start = ($page - 1) * $limt;
            $page_end = $page_start + $limt-1;
        }

        $where = [];
        if (!empty($info_id)){
            $where['b.info_id'] = $info_id;
        }

        if (!empty($date)){

            if ($date == 1){
                $where['a.date'] = date('Y-m-d');
            }elseif ($date == 2){
                $where['a.date'] = ['between time', [date('Y-m-d'), date('Y-m-d',strtotime('+6 days'))]];
            }
        }

        if (!empty($feedback)){
            $where['a.is_feedback'] = $feedback;
        }else{
            $where['a.is_feedback'] = 0;
        }


        if ($this->user_arr['pid'] == 0){
            $data = Db::table('fa_treatment')
                ->alias('a')
                ->field('a.id,a.order_id,b.code,c.name,a.name as names,a.date,a.msg')
                ->join('fa_diagnosis_order b','a.order_id=b.id')
                ->join('fa_info c','b.info_id=c.id')
                ->where($where)
                ->where('a.finish',1)
                ->where('c.user_id',$user_id)
                ->limit($page_start,$limt)
                ->order('date','desc')
                ->select();

            $total = Db::table('fa_treatment')
                ->alias('a')
                ->join('fa_diagnosis_order b','a.order_id=b.id')
                ->join('fa_info c','b.info_id=c.id')
                ->where('a.finish',1)
                ->where('c.user_id',$user_id)
                ->where($where)
                ->count();
        }else{
            $data = Db::table('fa_treatment')
                ->alias('a')
                ->field('a.id,a.order_id,b.code,c.name,a.name as names,a.date,a.msg')
                ->join('fa_diagnosis_order b','a.order_id=b.id')
                ->join('fa_info c','b.info_id=c.id')
                ->where($where)
                ->where('a.finish',1)
                ->where('c.binding',$user_id)
                ->limit($page_start,$limt)
                ->order('date','desc')
                ->select();

            $total = Db::table('fa_treatment')
                ->alias('a')
                ->join('fa_diagnosis_order b','a.order_id=b.id')
                ->join('fa_info c','b.info_id=c.id')
                ->where('a.finish',1)
                ->where('c.binding',$user_id)
                ->where($where)
                ->count();
        }


        if (!empty($data)){
            foreach ($data as $k=>$v){
                $count = Db::table('fa_treatment')
                    ->where('order_id',$v['order_id'])
                    ->count();
                $data[$k]['names'] = $v['names'].'(共'.$count.'次)';
            }
        }


        //组装数据
        $datas = [
            'page' => $page,
            'total' => $total,
            'limt' => $limt,
            'list' => $data,
        ];

        $this->success('成功',$datas);


    }


    /**
     * 反馈
     *
     */
    public function feedback(){
        $id = empty(request()->post('id')) ? $this->success('id不能为空'):request()->post('id');
        $msg = empty(request()->post('msg')) ? $this->success('msg不能为空'):request()->post('msg');

        $arr = Db::table('fa_treatment')
            ->where('id',$id)
            ->find();

        if (empty($arr)){
            $this->error('疗程表数据为空',[]);
        }

        $update = Db::table('fa_treatment')
            ->where('id',$id)
            ->update([
                'is_feedback' => 1,
                'msg' => $msg,
            ]);

        if ($update !== false){
            $this->success('成功',[]);
        }else{
            $this->error('失败',[]);
        }
    }

    /**
     * 历史生活信息
     *
     */
    public function life_list(){
        $info_id = empty(request()->post('info_id')) ? $this->error('info_id不能为空'):request()->post('info_id');
        $page = empty(request()->post('page')) ? 1:request()->post('page');//获取页码
        $limt = empty(request()->post('limt')) ? 10:request()->post('limt');//获取每页显示条数

        $user_id = $this->user_arr['id'];

        //分页
        if ($page == 1) {
            $page_start = 0;
            $page_end = $limt-1;
        } else {
            $page_start = ($page - 1) * $limt;
            $page_end = $page_start + $limt-1;
        }


        $data = Db::table('fa_life')
            ->alias('a')
            ->field('a.id,a.create_time')
            //->join('fa_diagnosis_order b','a.order_id=b.id')
            ->where('a.info_id',$info_id)
            ->limit($page_start,$limt)
            ->order('a.id','desc')
            ->select();

        $total = Db::table('fa_life')
            ->alias('a')
            //->join('fa_diagnosis_order b','a.order_id=b.id')
            ->where('a.info_id',$info_id)
            ->count();

        if (!empty($data)){
            foreach ($data as $k=>$v){
                $data[$k]['create_time'] = date('Y-m-d H:i:s',$v['create_time']);
            }
        }


        //组装数据
        $datas = [
            'page' => $page,
            'total' => $total,
            'limt' => $limt,
            'list' => $data,
        ];

        $this->success('成功',$datas);
    }


    /**
     * 生活信息详情
     *
     */
    public function life_detail(){
        $info_id = empty(request()->post('info_id')) ? $this->error('info_id不能为空'):request()->post('info_id');
        $id = empty(request()->post('id')) ? '':request()->post('id');

        $where = [];
        if (!empty($id)){
            $where['id'] = $id;
        }

        $data = Db::table('fa_life')
            ->field('id,smoke,drink,sports,diet,sleep,pee,excrement,menstruation,give_birth,create_time')
            ->where('info_id',$info_id)
            ->where($where)
            ->order('id','desc')
            ->find();


        if (!empty($data)){
            $data['create_time'] = date('Y-m-d H:i:s',$data['create_time']);
        }

        $this->success('成功',$data);

    }

    /**
     * 订单记录列表
     *
     */
    public function order_list(){
        $type = empty(request()->post('type')) ? $this->error('type不能为空'):request()->post('type');

        $page = empty(request()->post('page')) ? 1:request()->post('page');//获取页码
        $limt = empty(request()->post('limt')) ? 10:request()->post('limt');//获取每页显示条数

        //分页
        if ($page == 1) {
            $page_start = 0;
            $page_end = $limt-1;
        } else {
            $page_start = ($page - 1) * $limt;
            $page_end = $page_start + $limt-1;
        }

        $data = Db::table('fa_orders')
            ->alias('a')
            ->field('a.id,a.code,a.status,a.date,b.name,b.site,a.money,a.contacts,a.phone,a.site as sites,a.expressage,a.number,a.create_time,a.is_send')
            ->join('fa_products b','a.products_id=b.id','left')
            ->where(['a.type'=>$type,'a.user_id'=>$this->user_arr['id']])
            ->order('a.id','desc')
            ->limit($page_start,$limt)
            ->select();


        $total = Db::table('fa_orders')
            ->alias('a')
            ->join('fa_products b','a.products_id=b.id','left')
            ->where(['a.type'=>$type,'a.user_id'=>$this->user_arr['id']])
            ->count();

        if (!empty($data)){
            foreach ($data as $k=>$v){

                $pan = date('w',strtotime($v['date']));

                switch ($pan){
                    case 1:
                        $pan_time = '星期一';
                        break;
                    case 2:
                        $pan_time = '星期二';
                        break;
                    case 3:
                        $pan_time = '星期三';
                        break;
                    case 4:
                        $pan_time = '星期四';
                        break;
                    case 5:
                        $pan_time = '星期五';
                        break;
                    case 6:
                        $pan_time = '星期六';
                        break;
                    case 0:
                        $pan_time = '星期日';
                        break;
                }

                $data[$k]['date'] = $v['date'].' '.$pan_time;
                $data[$k]['money'] = $v['money']/100;
                $data[$k]['create_time'] = date('Y-m-d H:i:s',$v['create_time']);
            }
        }

        //组装数据
        $datas = [
            'page' => $page,
            'total' => $total,
            'limt' => $limt,
            'list' => $data,
        ];

        $this->success('查询成功',$datas);

    }

    /**
     * 修改查看密码
     *
     */
    public function change_password(){
        $old_password = empty(request()->post('old_password')) ? $this->error('old_password不能为空'):request()->post('old_password');
        $new_password = empty(request()->post('new_password')) ? $this->error('new_password不能为空'):request()->post('new_password');


        if(!is_numeric($new_password)){
            $this->error('查看密码必须是数字',[]);
        }

        if(strlen($new_password) != 6){
            $this->error('密码长度必须为6位',[]);
        }

        if ($old_password != $this->user_arr['password']){
            $this->error('原密码输入错误',[]);
        }

        if ($new_password == $this->user_arr['password']){
            $this->error('修改密码与原密码一致,请勿重复操作',[]);
        }

        $update = Db::table('fa_users')
            ->where('id',$this->user_arr['id'])
            ->update([
                'password' => $new_password,
                'update_time' => time(),
            ]);

        if ($update !== false){
            $this->success('成功',$update);
        }else{
            $this->error('失败',[]);
        }

    }

    /**
     *
     * 删除就诊人
     */
    public function del_info(){
        $id = empty(request()->post('id')) ? $this->error('id不能为空'):request()->post('id');

        $info_arr = Db::table('fa_info')
            ->where('id',$id)
            ->find();

        if (empty($info_arr)){
            $this->error('就诊人数据为空',[]);
        }

        if ($info_arr['user_id'] != $this->user_arr['id']){
            $this->error('就诊人不属于该账户',[]);
        }

        $update = Db::table('fa_info')
            ->where('id',$id)
            ->update([
                'user_id' => 0,
                'binding' => 0,
                'is_del' => 1,
                'update_time' => time(),
            ]);

        if ($update !== false){
            $this->success('成功',[]);
        }else{
            $this->error('失败',[]);
        }

    }

    /**
     * 储值钱包
     *
     */
    public function wallet(){
        $arr = [];
        if ($this->user_arr['pid'] == 0){
            $arr['money'] = $this->user_arr['money'];
            //已消费总金额
            $arr['consume_money'] = Db::table('fa_card_log')
                ->where(['user_id'=>$this->user_arr['id'],'type'=>2])
                ->sum('money');

            //历史充值总额
            $arr['recharge_money'] = Db::table('fa_card_log')
                ->where(['user_id'=>$this->user_arr['id'],'type'=>1])
                ->sum('money');
        }else{
            $this->success('成功',[]);
           $pid_arr = Db::table('fa_users')
               ->where('id',$this->user_arr['pid'])
               ->find();

           if (empty($pid_arr)){
               $this->error('主账号不存在',[]);
           }

            $arr['money'] = $pid_arr['money'];
            //已消费总金额
            $arr['consume_money'] = Db::table('fa_card_log')
                ->where(['user_id'=>$pid_arr['id'],'type'=>2])
                ->sum('money');

            //历史充值总额
            $arr['recharge_money'] = Db::table('fa_card_log')
                ->where(['user_id'=>$pid_arr['id'],'type'=>1])
                ->sum('money');

        }

        $arr['consume_money'] = number_format($arr['consume_money'],2,'.','');
        $arr['recharge_money'] = number_format($arr['recharge_money'],2,'.','');
        $this->success('成功',$arr);

    }

    /**
     * 储值钱包-记录列表
     *
     */
    public function wallet_list(){
        $type = empty(request()->post('type')) ? $this->error('type不能为空'):request()->post('type');

        $page = empty(request()->post('page')) ? 1:request()->post('page');//获取页码
        $limt = empty(request()->post('limt')) ? 10:request()->post('limt');//获取每页显示条数

        //分页
        if ($page == 1) {
            $page_start = 0;
            $page_end = $limt-1;
        } else {
            $page_start = ($page - 1) * $limt;
            $page_end = $page_start + $limt-1;
        }
        $where = [];
        if (!empty($type)){
            $where['type'] = $type;
        }

        if ($this->user_arr['pid'] == 0){
            $data = Db::table('fa_card_log')
                ->field('id,money,create_time,type')
                ->where($where)
                ->where(['user_id'=>$this->user_arr['id']])
                ->order('id','desc')
                ->limit($page_start,$limt)
                ->select();

            $total = Db::table('fa_card_log')
                ->where($where)
                ->where(['user_id'=>$this->user_arr['id']])
                ->count();
        }else{
            $this->success('查询成功',[]);
        }




        if (!empty($data)){
            foreach ($data as $k=>$v){
                $data[$k]['create_time'] = date('Y-m-d H:i:s',$v['create_time']);

                if ($v['type'] == 1){
                    $data[$k]['money'] = '+'.$v['money'];
                }elseif ($v['type'] == 2){
                    $data[$k]['money'] = '-'.$v['money'];
                }

            }
        }

        //组装数据
        $datas = [
            'page' => $page,
            'total' => $total,
            'limt' => $limt,
            'list' => $data,
        ];

        $this->success('查询成功',$datas);

    }


    /**
     * 邀请用户列表
     *
     */
    public function invite_list(){
        $page = empty(request()->post('page')) ? 1:request()->post('page');//获取页码
        $limt = empty(request()->post('limt')) ? 10:request()->post('limt');//获取每页显示条数

        //分页
        if ($page == 1) {
            $page_start = 0;
            $page_end = $limt-1;
        } else {
            $page_start = ($page - 1) * $limt;
            $page_end = $page_start + $limt-1;
        }


        $data = Db::table('fa_users')
            ->field('id,nickname,create_time')
            ->where(['invite'=>$this->user_arr['id']])
            ->order('id','desc')
            ->limit($page_start,$limt)
            ->select();

        $total = Db::table('fa_users')
            ->where(['invite'=>$this->user_arr['id']])
            ->count();

        if (!empty($data)){
            foreach ($data as $k=>$v){
                $data[$k]['create_time'] = date('Y-m-d H:i:s',$v['create_time']);
            }
        }

        //组装数据
        $datas = [
            'page' => $page,
            'total' => $total,
            'limt' => $limt,
            'list' => $data,
        ];

        $this->success('查询成功',$datas);
    }

    /**
     * 我的积分日志表
     *
     */
    public function integral_list(){
        $page = empty(request()->post('page')) ? 1:request()->post('page');//获取页码
        $limt = empty(request()->post('limt')) ? 10:request()->post('limt');//获取每页显示条数

        //分页
        if ($page == 1) {
            $page_start = 0;
            $page_end = $limt-1;
        } else {
            $page_start = ($page - 1) * $limt;
            $page_end = $page_start + $limt-1;
        }


        $data = Db::table('fa_integral_log')
            ->field('id,user_id,integral,type,way,create_time')
            ->where(['user_id'=>$this->user_arr['id']])
            ->order('id','desc')
            ->limit($page_start,$limt)
            ->select();

        $total = Db::table('fa_integral_log')
            ->where(['user_id'=>$this->user_arr['id']])
            ->count();

        if (!empty($data)){
            foreach ($data as $k=>$v){
                $data[$k]['create_time'] = date('Y-m-d H:i:s',$v['create_time']);

                if ($v['type'] == 1){
                    $data[$k]['integral'] = '-'.$v['integral'];
                }elseif ($v['type'] == 2){
                    $data[$k]['integral'] = '+'.$v['integral'];
                }

                if ($v['way'] == 1){
                    $data[$k]['way'] = '诊疗收费';
                }elseif ($v['way'] == 2){
                    $data[$k]['way'] = '预约收费';
                }

                unset($data[$k]['type']);

            }
        }

        //组装数据
        $datas = [
            'page' => $page,
            'total' => $total,
            'limt' => $limt,
            'list' => $data,
        ];

        $this->success('查询成功',$datas);
    }

    /**
     * 获取大客户数据
     *
     */
    public function get_big(){
        $arr = Db::table('fa_big')
            ->field('id,code,name,predict,consumption,group,can,already')
            ->where('phone',$this->user_arr['phone'])
            ->find();

        if (empty($arr)){
            $this->error('大客户数据为空',[]);
        }

        $this->success('查询成功',$arr);

    }

    /**
     * 大客户列表
     *
     */
    public function big_list(){
        $type = empty(request()->post('type')) ? $this->error('type不能为空'):request()->post('type');

        $page = empty(request()->post('page')) ? 1:request()->post('page');//获取页码
        $limt = empty(request()->post('limt')) ? 10:request()->post('limt');//获取每页显示条数


        $arr = Db::table('fa_big')
            ->where('phone',$this->user_arr['phone'])
            ->find();

        if (empty($arr)){
            $this->error('大客户数据为空',[]);
        }

        //分页
        if ($page == 1) {
            $page_start = 0;
            $page_end = $limt-1;
        } else {
            $page_start = ($page - 1) * $limt;
            $page_end = $page_start + $limt-1;
        }

        //1代表直客，2代表下级合伙人
        if ($type == 1){
            $data = Db::table('fa_users')
                ->field('id,nickname as name,image,binding_time')
                ->where(['big_id'=>$arr['id']])
                ->order('binding_time','desc')
                ->limit($page_start,$limt)
                ->select();

            $total = Db::table('fa_users')
                ->where(['big_id'=>$arr['id']])
                ->count();
        }elseif ($type == 2){
            $data = Db::table('fa_big')
                ->field('id,code,name,binding_time')
                ->where(['pid'=>$arr['id']])
                ->order('binding_time','desc')
                ->limit($page_start,$limt)
                ->select();

            $total = Db::table('fa_big')
                ->where(['pid'=>$arr['id']])
                ->count();
        }else{
            $this->error('type类型错误',[]);
        }

        if (!empty($data)){
            foreach ($data as $k=>&$v){
                $v['binding_time'] = date('Y-m-d H:i:s',$v['binding_time']);
            }
        }

        //组装数据
        $datas = [
            'page' => $page,
            'total' => $total,
            'limt' => $limt,
            'list' => $data,
        ];

        $this->success('查询成功',$datas);

    }

    /**
     * 结算提示
     *
     */
    public function hint(){
        $money = empty(request()->post('money')) ? $this->error('money不能为空'):request()->post('money');
        $type = empty(request()->post('type')) ? $this->error('type不能为空'):request()->post('type');
        $types = empty(request()->post('types')) ? $this->error('types不能为空'):request()->post('types');

        if (!is_numeric($money)){
            $this->error('money不是数字',[]);
        }

        $pan = [1,2];
        if (!in_array($type,$pan)){
            $this->error('type错误',[]);
        }

        if (!in_array($types,$pan)){
            $this->error('types错误',[]);
        }

        $arr = Db::table('fa_big')
            ->where('phone',$this->user_arr['phone'])
            ->find();

        if ($types == 1){
            if ($arr['consumption'] < 1000000){
                $ratio = 0.1;
                $ratios = '10%';
            }elseif (($arr['consumption'] >= 1000000) && ($arr['consumption'] < 3000000)){
                $ratio = 0.15;
                $ratios = '15%';
            }elseif ($arr['consumption'] >= 3000000){
                $ratio = 0.2;
                $ratios = '20%';
            }

            $moneys = $money*$ratio;
        }else{
            $moneys = $money*0.05;
            $ratios = '5%';
        }

        if ($type == 2){
            $moneys = $moneys*1.5;
        }



        $data = [
            'receivable' => empty($moneys) ? '0.00':floor($moneys*100)/100,
            //'ratio' => $ratios,
        ];

        $this->success('查询成功',$data);
    }

    /**
     * 结算
     *
     */
    public function settle_accounts(){
        var_dump(已弃用);die();
        $arr = Db::table('fa_big')
            ->where('phone',$this->user_arr['phone'])
            ->find();

        if (empty($arr)){
            $this->error('大客户数据为空',[]);
        }

        $pid_arr = Db::table('fa_big')
            ->where('id',$arr['pid'])
            ->find();

        $order_arr = Db::table('fa_diagnosis_order')
            ->alias('a')
            ->field('a.id,a.count_cost,a.other_cost,a.vip_discounts,a.iscounts_cost,a.vip_deduction,a.info_id,a.code')
            ->where(['status'=>['in','1,2'],'pay'=>['<>',7],'big_id'=>$arr['id'],'is_big'=>0])
            ->select();

        $insert_arr = [];
        $insert_arrs = [];
        $insert_log = [];


        $receivable = 0;
        $can = 0;
        $can_p = 0;
        $can_ps = 0;
        $moneys = 0;

        //开启事务
        Db::startTrans();
        if (!empty($order_arr)){
            foreach ($order_arr as $k=>$v){
                $money_q = number_format($v['count_cost']+$v['other_cost']-$v['vip_discounts']-$v['iscounts_cost']-$v['vip_deduction'],2,'.','');
                $receivable += $money_q;

                //直客收益
                $insert_arr[$k] = [
                    'big_id' => $arr['id'],
                    'info_id' => $v['info_id'],
                    'code' => $v['code'],
                    'moneys' => $money_q,
                    'create_time' => time(),
                    'type' => 1,
                    'id' => $v['id'],
                ];

                $pans = Db::table('fa_treatment')
                    ->field('id,finish')
                    ->where(['order_id'=>$v['id']])
                    ->count();

                $money_s = floor(($money_q*0.05)*100)/100;
                //团队收益
                $insert_arrs[$k] = [
                    'big_id' => $arr['pid'],
                    'info_id' => $v['info_id'],
                    'code' => $v['code'],
                    'money' => (floor((($money_s)/$pans)*100)/100)*$pans,
                    'moneys' => $money_q,
                    'create_time' => time(),
                    'type' => 2,
                    'subordinate' => $arr['id'],
                    'ratio' => '5%',
                    'id' => $v['id'],
                ];
            }

            if ($receivable == 0){
                $this->error('结算金额不能为0',[]);
            }

            if ($receivable < 1000000){
                $ratio = '10%';
                $ratios = 0.1;
            }elseif (($receivable >= 1000000) && ($receivable < 3000000)){
                $ratio = '15%';
                $ratios = 0.15;
            }elseif ($receivable >= 3000000){
                $ratio = '20%';
                $ratios = 0.2;
            }

            foreach ($insert_arr as $k=>$v){
                //$v['ratio'] = $ratio;
                $insert_arr[$k]['ratio'] = $ratio;
                $money = floor(($v['moneys']*$ratios)*100)/100;
                //$moneys += $money;

                $pan = Db::table('fa_treatment')
                    ->field('id,finish')
                    ->where(['order_id'=>$v['id']])
                    ->count();

                $pan_count = Db::table('fa_treatment')
                    ->field('id,finish')
                    ->where(['order_id'=>$v['id'],'finish'=>1])
                    ->count();

                if ($pan_count == $pan){
                    $can += $money;
                    $can_p += floor(($v['moneys']*0.05)*100)/100;
                    for ($i=1;$i<=$pan;$i++){
                        $insert_log[] = [
                            'big_id' => $v['big_id'],
                            'info_id' => $v['info_id'],
                            'code' => $v['code'],
                            'moneys' => $v['moneys'],
                            'money' => (floor(($money/$pan)*100)/100)*$pan,
                            'amount' => (floor(($money/$pan)*100)/100)*$pan,
                            'create_time' => time(),
                            'type' => $v['type'],
                            'subordinate' => 0,
                            'ratio' => $ratio,
                            'count' => $i.'/'.$pan,
                        ];
                    }

                }else{
                    $can_money = floor(($money/$pan)*100)/100;
                    $can += $can_money*$pan_count;

                    $ti_mpney = floor(($v['moneys']*0.05)*100)/100;
                    $can_p_money = floor(($ti_mpney/$pan)*100)/100;
                    $can_p += $can_p_money*$pan_count;

                    $can_ps += $can_p_money*($pan-$pan_count);

                    for ($i=1;$i<=$pan_count;$i++){
                        $insert_log[] = [
                            'big_id' => $v['big_id'],
                            'info_id' => $v['info_id'],
                            'code' => $v['code'],
                            'moneys' => $v['moneys'],
                            'money' => (floor(($money/$pan)*100)/100)*$pan,
                            'amount' => $can_money*$pan_count,
                            'create_time' => time(),
                            'type' => $v['type'],
                            'subordinate' => 0,
                            'ratio' => $ratio,
                            'count' => $i.'/'.$pan,
                        ];
                    }

                }

                //$v['money'] = (floor(($money/$pan)*100)/100)*$pan;
                $insert_arr[$k]['money'] = (floor(($money/$pan)*100)/100)*$pan;
                $moneys += (floor(($money/$pan)*100)/100)*$pan;


                unset($insert_arr[$k]['id']);
            }

            foreach ($insert_arrs as $k=>$v){
                $pan = Db::table('fa_treatment')
                    ->field('id,finish')
                    ->where(['order_id'=>$v['id']])
                    ->count();

                $pan_count = Db::table('fa_treatment')
                    ->field('id,finish')
                    ->where(['order_id'=>$v['id'],'finish'=>1])
                    ->count();

                if ($pan_count == $pan){
                    for ($i=1;$i<=$pan;$i++){
                        $insert_log[] = [
                            'big_id' => $v['big_id'],
                            'info_id' => $v['info_id'],
                            'code' => $v['code'],
                            'moneys' => $v['moneys'],
                            'money' => $v['money'],
                            'amount' => floor(($v['money']/$pan)*100)/100,
                            'create_time' => time(),
                            'type' => $v['type'],
                            'subordinate' => $v['subordinate'],
                            'ratio' => $v['ratio'],
                            'count' => $i.'/'.$pan,
                        ];
                    }

                }else{
                    for ($i=1;$i<=$pan_count;$i++){
                        $insert_log[] = [
                            'big_id' => $v['big_id'],
                            'info_id' => $v['info_id'],
                            'code' => $v['code'],
                            'moneys' => $v['moneys'],
                            'money' => $v['money'],
                            'amount' => floor(($v['money']/$pan)*100)/100,
                            'create_time' => time(),
                            'type' => $v['type'],
                            'subordinate' => $v['subordinate'],
                            'ratio' => $v['ratio'],
                            'count' => $i.'/'.$pan,
                        ];
                    }

                }
                unset($insert_arrs[$k]['id']);
            }

            $receivables = floor(($moneys-$can)*100)/100;

            if (!empty($insert_arr)){
                $insert = Db::table('fa_big_log')
                    ->insertAll($insert_arr);
            }else{
                $insert = 1;
            }

            if (!empty($insert_arrs)){
                $inserts = Db::table('fa_big_log')
                    ->insertAll($insert_arrs);
            }else{
                $inserts = 1;
            }

            if (!empty($insert_log)){
                $insertl = Db::table('fa_big_logss')
                    ->insertAll($insert_log);
            }else{
                $insertl = 1;
            }


            $update = Db::table('fa_diagnosis_order')
                ->where(['status'=>['in','1,2'],'pay'=>['<>',7],'big_id'=>$arr['id'],'is_big'=>0])
                ->update([
                    'is_big' => 1,
                ]);

            $updates = Db::table('fa_big')
                ->where('id',$arr['id'])
                ->update([
                    'predict' => $arr['predict']+$receivables,
                    'can' => $arr['can']+$can,
                    'update_time' => time(),
                ]);

            $updates_p = Db::table('fa_big')
                ->where('id',$arr['pid'])
                ->update([
                    'predict' => $pid_arr['predict']+$can_ps,
                    'can' => $pid_arr['can']+$can_p,
                    'update_time' => time(),
                ]);

        }else{
            $insert = 1;
            $update = 1;
            $inserts = 1;
            $updates = 1;
            $updates_p = 1;
            $insertl = 1;
        }

        if (($insert !== false) && ($update !== false) && ($inserts !== false) && ($updates !== false) && ($updates_p !== false) && ($insertl !== false)){
            //事务提交
            Db::commit();
            $this->success('成功',[]);
        }else{
            //事务回滚
            Db::rollback();
            $this->error('失败',[]);
        }


    }

    /**
     * 兑换
     *
     */
    public function exchange(){
        $type = empty(request()->post('type')) ? $this->error('type不能为空'):request()->post('type');
        $types = empty(request()->post('types')) ? $this->error('types不能为空'):request()->post('types');
        $money = empty(request()->post('money')) ? $this->error('money不能为空'):request()->post('money');

        if (!is_numeric($money)){
            $this->error('money不是数字',[]);
        }

        if (floatval($money) == 0 ){
            $this->error('money不能为0',[]);
        }

        if ($money < 1){
            $this->error('金额不能低于1',[]);
        }

        $money = floor($money*100)/100;

        $pan = [1,2];

        if (!in_array($type,$pan)){
            $this->error('type错误',[]);
        }

        if (!in_array($types,$pan)){
            $this->error('types错误',[]);
        }

        $arr = Db::table('fa_big')
            ->where('phone',$this->user_arr['phone'])
            ->find();

        if (empty($arr)){
            $this->error('大客户数据为空',[]);
        }

        //事务开始
        Db::startTrans();

        if ($types == 1){
            if (($arr['consumption']-$money) < 0){
                $this->error('疗程消费金额不足',[]);
            }

            if ($arr['consumption'] < 1000000){
                $ratio = 0.1;
                $can = floor($money*0.1*100)/100;
            }elseif (($arr['consumption'] >= 1000000) && ($arr['consumption'] < 3000000)){
                $ratio = 0.15;
                $can = floor($money*0.15*100)/100;
            }elseif ($arr['consumption'] >= 3000000){
                $ratio = 0.2;
                $can = floor($money*0.2*100)/100;
            }

            $update = Db::table('fa_big')
                ->where('id',$arr['id'])
                ->update([
                    'consumption' => $arr['consumption']-$money,
                    'can' => $arr['can']-$can,
                    'update_time' => time(),
                ]);

        }else{
            if (($arr['group']-$money) < 0){
                $this->error('团队消费金额不足',[]);
            }

            $can = floor($money*0.05*100)/100;
            $ratio = 0.05;

            $update = Db::table('fa_big')
                ->where('id',$arr['id'])
                ->update([
                    'group' => $arr['group']-$money,
                    'can' => $arr['can']-$can,
                    'update_time' => time(),
                ]);
        }


        $insert = Db::table('fa_big_logs')
            ->insertGetId([
                'big_id' => $arr['id'],
                'money' => $money,
                'status' => 0,
                'create_time' => time(),
                'type' => $type,
                'types' => $types,
                'ratio' => $ratio,
                'amount' => $can,
            ]);

        if(($insert !== false) && ($update !== false)){
            //事务提交
            Db::commit();
            $this->success('成功',[]);
        }else{
            //事务回滚
            Db::rollback();
            $this->error('失败',[]);
        }

    }

    /**
     * 日志列表数据
     *
     */
    public function logs_list(){
        $type = empty(request()->post('type')) ? $this->error('type不能为空'):request()->post('type');

        $page = empty(request()->post('page')) ? 1:request()->post('page');//获取页码
        $limt = empty(request()->post('limt')) ? 10:request()->post('limt');//获取每页显示条数


        $arr = Db::table('fa_big')
            ->where('phone',$this->user_arr['phone'])
            ->find();

        if (empty($arr)){
            $this->error('大客户数据为空',[]);
        }

        //分页
        if ($page == 1) {
            $page_start = 0;
            $page_end = $limt-1;
        } else {
            $page_start = ($page - 1) * $limt;
            $page_end = $page_start + $limt-1;
        }

        //1代表直客，2代表团队奖励，3代表提现，4代表兑换
        if ($type == 1){
            $data = Db::table('fa_big_logss')
                ->alias('a')
                ->field('a.id,b.number,a.moneys,a.amount,a.create_time,c.code,c.id as order_id,a.count as plan')
                ->join('fa_info b','a.info_id=b.id','left')
                ->join('fa_diagnosis_order c','a.code=c.code','left')
                ->where(['a.big_id'=>$arr['id'],'a.type'=>1])
                ->order('a.id','desc')
                ->limit($page_start,$limt)
                ->select();

            $total = Db::table('fa_big_logss')
                ->alias('a')
                ->join('fa_info b','a.info_id=b.id','left')
                ->join('fa_diagnosis_order c','a.code=c.code','left')
                ->where(['a.big_id'=>$arr['id'],'a.type'=>1])
                ->count();

            if (!empty($data)){
                foreach ($data as $k=>&$v){
                    $v['create_time'] = date('Y-m-d H:i:s',$v['create_time']);
                }
            }

        }elseif ($type == 2){
            $data = Db::table('fa_big_logss')
                ->alias('a')
                ->field('a.id,b.number,a.moneys,a.amount,a.create_time,c.code,d.code as partner_code,c.id as order_id,a.count as plan')
                ->join('fa_info b','a.info_id=b.id','left')
                ->join('fa_diagnosis_order c','a.code=c.code','left')
                ->join('fa_big d','a.subordinate=d.id','left')
                ->where(['a.big_id'=>$arr['id'],'a.type'=>2])
                ->order('a.id','desc')
                ->limit($page_start,$limt)
                ->select();

            $total = Db::table('fa_big_logss')
                ->alias('a')
                ->join('fa_info b','a.info_id=b.id','left')
                ->join('fa_diagnosis_order c','a.code=c.code','left')
                ->join('fa_big d','a.subordinate=d.id','left')
                ->where(['a.big_id'=>$arr['id'],'a.type'=>2])
                ->count();

            if (!empty($data)){
                foreach ($data as $k=>&$v){
                    $v['create_time'] = date('Y-m-d H:i:s',$v['create_time']);
                }
            }
        }elseif ($type == 3){
            $data = Db::table('fa_big_logs')
                ->field('id,money,amount,status,create_time')
                ->where(['big_id'=>$arr['id'],'type'=>1])
                ->order('id','desc')
                ->limit($page_start,$limt)
                ->select();

            $total = Db::table('fa_big_logs')
                ->field('id,money,status,create_time')
                ->where(['big_id'=>$arr['id'],'type'=>1])
                ->count();

            if (!empty($data)){
                foreach ($data as $k=>&$v){
                    $v['create_time'] = date('Y-m-d H:i:s',$v['create_time']);

                    switch ($v['status']){
                        case 0:
                            $v['status'] = '审核中';
                            break;
                        case 1:
                            $v['status'] = '成功';
                            break;
                        case 2:
                            $v['status'] = '驳回';
                            break;
                        default:
                            $v['status'] = '';
                            break;
                    }
                }
            }

        }elseif ($type == 4){
            $data = Db::table('fa_big_logs')
                ->field('id,money,amount,status,create_time')
                ->where(['big_id'=>$arr['id'],'type'=>2])
                ->order('id','desc')
                ->limit($page_start,$limt)
                ->select();

            $total = Db::table('fa_big_logs')
                ->field('id,money,status,create_time')
                ->where(['big_id'=>$arr['id'],'type'=>2])
                ->count();

            if (!empty($data)){
                foreach ($data as $k=>&$v){
                    $v['create_time'] = date('Y-m-d H:i:s',$v['create_time']);

                    switch ($v['status']){
                        case 0:
                            $v['status'] = '审核中';
                            break;
                        case 1:
                            $v['status'] = '成功';
                            break;
                        case 2:
                            $v['status'] = '驳回';
                            break;
                        default:
                            $v['status'] = '';
                            break;
                    }
                }
            }
        }




        //组装数据
        $datas = [
            'page' => $page,
            'total' => $total,
            'limt' => $limt,
            'list' => $data,
        ];

        $this->success('查询成功',$datas);

    }

}
